<?php

namespace App\Exceptions;

use App\Traits\UnifiedResponse;
use ErrorException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    use UnifiedResponse;

    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        // 500 ErrorException
        $this->reportable(function (ErrorException $e) {
            $message = $e->getMessage() . "；LINE：" . $e->getFile() . "(" . $e->getLine() . ")";
            return $this->exception($message)->errorHttpInternalServerError();
        });

        // 资源不存在404
        $this->renderable(function (NotFoundHttpException $e) {
            return $this->errorHttpNotFound();
        });

        // 用户认证不通过异常处理
        $this->renderable(function (AuthenticationException $e) {
            return $this->errorLoginNotToken();
        });

        // 接口请求频繁处理
        $this->renderable(function (ThrottleRequestsException $e) {
            return $this->error(trans('common.operation_fast'));
        });

        // 表单验证不通过处理
        $this->renderable(function (ValidationException $e) {
            $errorMsg = $e->validator->errors()->first();
            return $this->error($errorMsg);
        });

        // 附件上传
        $this->renderable(function (FileException $e) {
            return $this->errorUploaded($e->getMessage());
        });

        // 其他
        $this->reportable(function (Throwable $e) {
            $message = $e->getMessage() . "；LINE：" . $e->getFile() . "(" . $e->getLine() . ")";
            return $this->exception($message)->errorHttpInternalServerError();
        });
    }
}
